02.01.06 转换为其他Python对象
将深度学习框架定义的张量转换为NumPy张量(ndarray)很容易,反之也同样容易。 转换后的结果不共享内存。 这个小的不便实际上是非常重要的:当在CPU或GPU上执行操作的时候, 如果Python的NumPy包也希望使用相同的内存块执行其他操作,人们不希望停下计算来等它。
import torch,numpy as np
X = torch.arange(12, dtype=torch.float32).reshape((3,4))
A = X.numpy()
B = torch.tensor(A)
print(type(A), type(B))
返回值:
<class 'numpy.ndarray'> <class 'torch.Tensor'>
要将大小为1的张量转换为Python标量,我们可以调用item函数或Python的内置函数。
import torch,numpy as np
a = torch.arange(12, dtype=torch.float32).reshape((3,4))
b=a.numpy()
c = torch.tensor([3.5])
print(a)
print(a[0, 2].item()) # 获取单个元素标量
print(a.tolist()) # 转换为嵌套列表
print(float(c))
print(int(c))
返回值:
tensor([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]])
2
[[0.0, 1.0, 2.0, 3.0], [4.0, 5.0, 6.0, 7.0], [8.0, 9.0, 10.0, 11.0]]
3.5
3
补充说明
float(a) 和 int(a) 本质上是调用 a.__float__() 和 a.__int__(),这些方法同样要求张量是标量,因此不能用于多元素张量。
如果确实需要将所有元素转为 Python 标量组成的列表,推荐使用 .tolist() 或 .numpy().tolist()